export class MediaStreamManager {
    private localStream: MediaStream | null = null;
    private constraints: MediaStreamConstraints;
    private noCameraStream: MediaStream | null = null;
  
    constructor(
      constraints: MediaStreamConstraints = { video: true, audio: true }
    ) {
      this.constraints = constraints;
    }
  
    public async getLocalStream(): Promise<MediaStream> {
      if (this.localStream) return this.localStream;
  
      try {
        this.localStream = await navigator.mediaDevices.getUserMedia(
          this.constraints
        );
        return this.localStream;
      } catch (error) {
        console.error("Failed to get local stream:", error);
        return this.createNoCameraStream();
      }
    }
  
    private createNoCameraStream(): MediaStream {
      if (this.noCameraStream) return this.noCameraStream;
  
      const canvas = document.createElement("canvas");
      canvas.width = 640;
      canvas.height = 480;
      const ctx = canvas.getContext("2d");
  
      if (ctx) {
        ctx.fillStyle = "#cccccc";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
  
        ctx.fillStyle = "#666666";
        ctx.font = "24px Arial";
        ctx.textAlign = "center";
        ctx.fillText(
          "No camera available",
          canvas.width / 2,
          canvas.height / 2 - 12
        );
      }
  
      const updateCanvas = () => {
        if (ctx) {
          ctx.fillStyle = "#cccccc";
          ctx.fillRect(0, 0, canvas.width, canvas.height);
  
          ctx.fillStyle = "#666666";
          ctx.font = "24px Arial";
          ctx.textAlign = "center";
          ctx.fillText(
            "No camera available",
            canvas.width / 2,
            canvas.height / 2 - 12
          );
        }
        requestAnimationFrame(updateCanvas);
      };
      requestAnimationFrame(updateCanvas);
  
      const videoStream = canvas.captureStream(30);
      const videoTrack = videoStream.getVideoTracks()[0];
      if (!videoTrack) {
        throw new Error("无法创建视频轨道");
      }
  
      let audioTrack: MediaStreamTrack | null = null;
      if (this.constraints.audio) {
        try {
          const audioContext = new AudioContext();
          const silence = audioContext.createBuffer(1, 1, 44100);
          const source = audioContext.createBufferSource();
          source.buffer = silence;
          const destination = audioContext.createMediaStreamDestination();
          source.connect(destination);
          source.start(0);
          source.loop = true;
          audioTrack = destination.stream.getAudioTracks()[0];
        } catch (e) {
          console.error("创建音频轨道失败:", e);
        }
      }
  
      this.noCameraStream = new MediaStream();
      this.noCameraStream.addTrack(videoTrack);
      if (audioTrack) {
        this.noCameraStream.addTrack(audioTrack);
      }
  
      console.log("创建替代媒体流成功", {
        videoTracks: this.noCameraStream.getVideoTracks().length,
        audioTracks: this.noCameraStream.getAudioTracks().length,
      });
  
      return this.noCameraStream;
    }
  
    public getTracks(): MediaStreamTrack[] {
      if (!this.localStream) return [];
      return this.localStream.getTracks();
    }
  
    public stopLocalStream(): void {
      if (this.localStream) {
        this.localStream.getTracks().forEach((track) => track.stop());
        this.localStream = null;
      }
    }
  
    public async updateConstraints(
      newConstraints: MediaStreamConstraints
    ): Promise<MediaStream> {
      this.constraints = newConstraints;
      this.stopLocalStream();
      return this.getLocalStream();
    }
  }
  